from tortoise.expressions import Q

from app.core.crud import CRUDBase
from app.models.content import Content,ContentCategory
from app.schemas.content import ContentCreate,ContentUpdate



class ContentController(CRUDBase[Content, ContentCreate, ContentUpdate]):
    def __init__(self):
        super().__init__(model=Content)

    async def content_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search).select_related("parent")
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('order')
        data = [await obj.to_dict(m2m=True) for obj in objs]
        return total, data

    async def content_get(self,data_id:int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    async def content_create(self, obj_in: ContentCreate):
        # 关联数据
        obj_in.parent = await ContentCategory.get(id=obj_in.parent)
        await self.create(obj_in=obj_in)
        return True

    async def content_update(self, obj_in: ContentUpdate):
        # 关联数据
        obj_in.parent = await ContentCategory.get(id=obj_in.parent)
        await self.update(id=obj_in.id, obj_in=obj_in)
        return True

    async def content_delete(self, data_id: int):
        await self.remove(id=data_id)
        return True

content_controller = ContentController()
